<!-- 用户编辑 -->
<template>
  <div class="user-edit-container">
    <el-form
      ref="userForm"
      :model="userForm"
      :rules="rules"
      label-width="100px"
      class="user-form"
    >
      <el-form-item label="登录名" prop="loginName">
        <el-input v-model="userForm.loginName" />
      </el-form-item>

      <el-form-item label="员工姓名" prop="empName">
        <el-input v-model="userForm.empName" />
      </el-form-item>

      <el-form-item label="密码" prop="password" v-if="!isEdit">
        <el-input v-model="userForm.password" type="password" />
      </el-form-item>

      <el-form-item label="职位" prop="position">
        <el-input v-model="userForm.position" />
      </el-form-item>

      <el-form-item label="邮箱" prop="email">
        <el-input v-model="userForm.email" />
      </el-form-item>

      <el-form-item label="手机号" prop="phoneNumber">
        <el-input v-model="userForm.phoneNumber" />
      </el-form-item>

      <el-form-item label="薪资" prop="salary">
        <el-input-number v-model="userForm.salary" :precision="2" :min="0" />
      </el-form-item>

      <el-form-item>
        <el-button type="primary" @click="submitForm">提交</el-button>
        <el-button @click="goBack">返回</el-button>
      </el-form-item>
    </el-form>
  </div>
</template>

<script>
import { addEmployee, updateEmployee, getEmployeeDetail } from '@/api/employee'

export default {
  name: 'UserEdit',
  props: {
    id: {
      type: String,
      default: ''
    }
  },
  data() {
    const validateEmail = (rule, value, callback) => {
      const emailRegex = /^[^\s@]+@[^\s@]+\.[^\s@]+$/
      if (value && !emailRegex.test(value)) {
        callback(new Error('请输入正确的邮箱格式'))
      } else {
        callback()
      }
    }

    const validatePhone = (rule, value, callback) => {
      const phoneRegex = /^1[3-9]\d{9}$/
      if (value && !phoneRegex.test(value)) {
        callback(new Error('请输入正确的手机号格式'))
      } else {
        callback()
      }
    }

    return {
      userForm: {
        loginName: '',
        empName: '',
        password: '',
        position: '',
        email: '',
        phoneNumber: '',
        salary: 0
      },
      rules: {
        loginName: [
          { required: true, message: '请输入登录名', trigger: 'blur' }
        ],
        empName: [
          { required: true, message: '请输入员工姓名', trigger: 'blur' }
        ],
        password: [
          { required: !this.isEdit, message: '请输入密码', trigger: 'blur' }
        ],
        email: [
          { required: true, message: '请输入邮箱', trigger: 'blur' },
          { validator: validateEmail, trigger: 'blur' }
        ],
        phoneNumber: [
          { required: true, message: '请输入手机号', trigger: 'blur' },
          { validator: validatePhone, trigger: 'blur' }
        ],
        salary: [
          { required: true, message: '请输入薪资', trigger: 'blur' }
        ]
      }
    }
  },
  computed: {
    isEdit() {
      return !!this.id
    }
  },
  created() {
    if (this.id) {
      this.getUserDetail()
    }
  },
  methods: {
    async getUserDetail() {
      try {
        const res = await getEmployeeDetail(this.id)
        if (res.code === 200) {
          const { 
            loginName,
            empName,
            position,
            email,
            phoneNumber,
            salary
          } = res.data
          
          this.userForm = {
            employeeId: this.id,
            loginName,
            empName,
            position,
            email,
            phoneNumber,
            salary: Number(salary)
          }
        }
      } catch (error) {
        console.error('获取用户详情失败:', error)
        this.$message.error('获取用户详情失败')
      }
    },
    submitForm() {
      this.$refs.userForm.validate(async valid => {
        if (valid) {
          try {
            const api = this.isEdit ? updateEmployee : addEmployee
            const res = await api(this.userForm)
            if (res.code === 200) {
              this.$message.success(`${this.isEdit ? '更新' : '新增'}成功`)
              this.goBack()
            }
          } catch (error) {
            console.error(`${this.isEdit ? '更新' : '新增'}失败:`, error)
            this.$message.error(error.response?.data?.message || `${this.isEdit ? '更新' : '新增'}失败`)
          }
        }
      })
    },
    goBack() {
      this.$router.push('/user/list')
    }
  }
}
</script>

<style lang="less" scoped>
.user-edit-container {
  padding: 20px;
  
  .user-form {
    max-width: 600px;
    margin: 0 auto;
    background: #fff;
    padding: 20px;
    border-radius: 4px;
    box-shadow: 0 1px 4px rgba(0, 21, 41, 0.08);
  }
}
</style>
